import { reactive, readonly, toRaw } from 'vue'
import Cache from '../utils/cache/index.js'
import { defineStore } from './state.js'

function kebabCase(str: string): string {
  str = str.replace(str.charAt(0), str.charAt(0).toLocaleLowerCase())
  return str.replace(/([a-z])([A-Z])/g, (_, p1, p2) => `${p1}-${p2.toLowerCase()}`)
}
/**
 * css变量转map
 */
export function cssVarsToMapThemeVars(styleStr: string) {
  const style: Record<string, string> = {}
  styleStr.replace(/\n|\r/g, '').split(';').filter(Boolean).forEach((e: string) => {
    const [key, val] = e.split(':')
    const keyNoSpace = key.replace(/\s/g, '')
    if (key) {
      style[keyNoSpace] = val.replace(/^\s/, '')
    }
  })
  return style
}
export function mapThemeVarsToCSSVars(themeVars: Record<string, string>, prefix: string = '--mui-') {
  if (!themeVars) return {}
  const cssVars: Record<string, string> = {}
  for (const key in themeVars) {
    cssVars[`${prefix}${kebabCase(key)}`] = themeVars[key]
  }
  return cssVars
}

const THEME_KEY = 'gfjtyrdfshsearhjkmjhlg-theme'
// 主题
const useThemeStore = defineStore(() => {
  const themeLocal = Cache.get<{ name: string, style: Record<string, string> }>(THEME_KEY) || {}
  const theme = reactive({
    name: themeLocal.name || 'default',
    style: themeLocal.style || {}
  })

  function setTheme(name: string, style: string | Record<string, string>, prefix: string = '--mui-') {
    theme.name = name
    if (typeof style === 'string') {
      theme.style = cssVarsToMapThemeVars(style)
    }
    else {
      const styleTemp: Record<string, string> = {}
      for (const key in style) {
        styleTemp[`${prefix}${kebabCase(key)}`] = style[key]
      }
      theme.style = styleTemp
    }
    Cache.set(THEME_KEY, toRaw(theme))
  }

  return {
    theme: readonly(theme),
    setTheme,
    cssVarsToMapThemeVars,
    mapThemeVarsToCSSVars
  }
})
export interface Theme {
  name: string
  style: string | Record<string, string>
}
/**
 * 初始化主题 {name:'defaul', style: { colorPrimary: '#ff0000' }}
 * @param {object} theme
 */
export function initTheme(theme?: Theme, prefix: string = '--mui-') {
  if (!theme) return
  const themeStore = useThemeStore()
  themeStore.setTheme(theme.name, theme.style, prefix)
}
export default useThemeStore
